//
//  CRSessioCRageContentView.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/10/23.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "CRSessionImageContentView.h"
#import <YYKit/YYImage.h>
#import "CRLoadProgressView.h"
#import "CRMessageModel.h"
#import "CRImageObject.h"

@interface CRSessionImageContentView()

@property (nonatomic,strong,readwrite) YYAnimatedImageView * imageView;

@property (nonatomic,strong) CRLoadProgressView * progressView;

@end

@implementation CRSessionImageContentView

- (instancetype)initSessionMessageContentView {
    
    self = [super initSessionMessageContentView];
    if (self) {
        self.opaque = YES;
        _imageView  = [[YYAnimatedImageView alloc] initWithFrame:CGRectZero];
        _imageView.backgroundColor = [UIColor whiteColor];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:_imageView];
        _progressView = [[CRLoadProgressView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        _progressView.maxProgress = 1.0f;
        [self addSubview:_progressView];
    }
    return self;
}

- (void)refresh:(CRMessageModel *)data
{
    [super refresh:data];
    _imageView.image = nil;
    CRImageObject * imageObject = (CRImageObject*)self.model.message.messageObject;
    
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:imageObject.thumbPath];
    YYImage *image = [YYImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
    _imageView.image = image;
    
//    self.progressView.hidden     = self.model.message.isOutgoingMsg ? (self.model.message.deliveryState != CRMessageDeliveryStateDelivering) : (self.model.message.attachmentDownloadState != CRMessageAttachmentDownloadStateDownloading);
//    if (!self.progressView.hidden) {
//        [self.progressView setProgress:[[[CRSDK sharedSDK] chatManager] messageTransportProgress:self.model.message]];
//    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    UIEdgeInsets contentInsets = self.model.contentViewInsets;
    CGFloat tableViewWidth = self.superview.width;
    CGSize contentSize = [self.model contentSize:tableViewWidth];
    CGRect imageViewFrame = CGRectMake(contentInsets.left, contentInsets.top, contentSize.width, contentSize.height);
    self.imageView.frame  = imageViewFrame;
    _progressView.frame   = self.bounds;
    
    CALayer *maskLayer = [CALayer layer];
    maskLayer.cornerRadius = 13.0;
    maskLayer.backgroundColor = [UIColor blackColor].CGColor;
    maskLayer.frame = self.imageView.bounds;
    self.imageView.layer.mask = maskLayer;
}


- (void)onTouchUpInside:(id)sender
{
    CRKitEvent *event = [[CRKitEvent alloc] init];
    event.eventName = CRKitEventNameTapContent;
    event.messageModel = self.model;
    [self.delegate onCatchEvent:event];
}

- (void)updateProgress:(float)progress
{
    if (progress > 1.0) {
        progress = 1.0;
    }
    self.progressView.progress = progress;
}

@end
